<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;

class UserVip extends Model
{
    protected function getOptions(): array
    {
        return [
            'autoWriteTimestamp' => true,
            'jsonAssoc'          => true,
            'price'              => 'float',
        ];
    }

    /**
     * 关联VIP记录
     */
    public function vipRecords()
    {
        return $this->hasMany('UserVipRecord', 'vip_id');
    }

    public function getPriceAttr($value)
    {
        return floatval($value);
    }

    /**
     * 获取所有启用的VIP等级
     * @return array
     */
    public static function getEnabledVips()
    {
        return self::where('status', 1)
            ->order('price', 'asc')
            ->select()
            ->toArray();
    }

    /**
     * 根据ID获取VIP信息
     * @param int $id VIP ID
     * @return array|null
     */
    public static function getVipInfo($id)
    {
        $vip = self::find($id);
        return $vip ? $vip->toArray() : null;
    }

    /**
     * 购买VIP会员
     * @param int $userId 用户ID
     * @param int $vipId VIP ID
     * @param int $orderId 支付网关ID
     * @return string|bool
     */
    public static function purchaseVip($userId, $vipId, $channelId)
    {
        $vip = self::find($vipId);
        if (!$vip || $vip->status != 1) {
            return false;
        }

        $user = User::find($userId);
        if (!$user) {
            return false;
        }

        // 计算 channel_account_id
        $channel = Channel::find($channelId);
        if (!$channel) {
            return false;
        }
        // 随机选择一个可用账号
        $channelAccounts = $channel->accounts()->where('status', 1)->select();
        if ($channelAccounts->isEmpty()) {
            return false;
        } else {
            $channelAccountsArr = $channelAccounts->toArray();
            $randomIndex        = array_rand($channelAccountsArr);
            $channelAccountId   = $channelAccountsArr[$randomIndex]['id'];
        }

        // 计算价格
        $total_price = $vip->price;

        // 计算开始和结束时间
        $startTime = 0;

        // 如果用户已有VIP且未过期，则在原有基础上延长
        $currentVip = $user->currentVip();
        if ($currentVip && strtotime($currentVip->end_time) > time()) {
            $startTime = $currentVip->end_time;
        }

        $endTime = date('Y-m-d H:i:s', strtotime($startTime) + $vip->duration * 86400);

        $trade_no = generate_trade_no("V");
        OrderMaster::create(["trade_no" => $trade_no, "model" => 'UserVipRecord']);
        // 创建VIP记录
        UserVipRecord::create([
            'user_id'            => $userId,
            'vip_id'             => $vipId,
            'start_time'         => $startTime,
            'end_time'           => $endTime,
            'channel_id'         => $channelId,
            'channel_account_id' => $channelAccountId,
            'total_price'        => $total_price,
            'trade_no'           => $trade_no,
            'status'             => 0,
            'order_status'       => 0,
            'create_time'        => date('Y-m-d H:i:s'),
            'update_time'        => date('Y-m-d H:i:s')
        ]);

        // 更新用户表中的VIP过期时间
        $user->vip_expire_time = $endTime;
        $user->save();



        return $trade_no;
    }

}